<template>
  <form class="search" @submit.prevent="onSubmit" @click="focusInput">
    <div class="engine-wrap">
      <button ref="engineBtn" class="engine" type="button" :title="currentEngine?.name" @click="toggleList">
        <img v-if="currentEngine?.icon" class="logo" :src="currentEngine.icon" alt="logo" />
        <span v-else>{{ currentEngine?.name?.slice(0,1) || '搜' }}</span>
      </button>
      <teleport to="body">
        <div v-if="showList" class="engine-list" :style="menuStyle" @click.stop>
          <button v-for="e in engines.list" :key="e.id" class="engine-item" @click="choose(e.id)">
            <img v-if="e.icon" class="logo sm" :src="e.icon" alt="" />
            <span v-else class="dot">{{ e.name.slice(0,1) }}</span>
            <span class="nm">{{ e.name }}</span>
          </button>
        </div>
      </teleport>
    </div>
    <input ref="inputEl" v-model="q" type="text" :placeholder="placeholder" />
  </form>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import type { CSSProperties } from 'vue';
import { useEngines } from '../../core/store/useEngines';
import { composeUrl } from '../../core/utils/validators';
import { useSettings } from '../../core/store/useSettings';

const engines = useEngines();
const settings = useSettings();

const q = ref('');
const inputEl = ref<HTMLInputElement | null>(null);
const placeholder = '输入搜索内容';
const showList = ref(false);
const engineBtn = ref<HTMLButtonElement | null>(null);
const menuPos = ref<{left:number; top:number}>({ left: 0, top: 0 });
// 引擎图标：优先使用本地 dataURL（engines.store 在 init/reload 时会自动抓取并持久化）

const currentEngine = computed(() => {
  // 强制响应式依赖追踪
  const enginesList = engines.list; // 确保追踪list变化
  const enginesDefaultId = engines.defaultId; // 确保追踪defaultId变化
  const settingsDefaultSearchId = settings.settings?.defaultSearchId; // 确保追踪settings变化
  
  // 优先使用engines store的defaultId
  const engineId = enginesDefaultId || settingsDefaultSearchId || 'baidu';
  const hit = engines.byId?.get?.(engineId) || enginesList.find(e => e.id === engineId);
  const result = hit || engines.defaultEngine || enginesList[0];
  
  return result;
});

const menuStyle = computed<CSSProperties>(() => ({ 
  position: 'fixed', 
  left: menuPos.value.left + 'px', 
  top: menuPos.value.top + 'px', 
  zIndex: 100003 
}));

// 事件处理函数
function onDoc(e: MouseEvent){
  const t = e.target as HTMLElement;
  // 兼容 teleport 到 body 的下拉菜单：点击 .engine-list 内部不视为外部点击
  if(!t.closest('.engine-wrap, .engine-list')) showList.value = false;
}

function onKeydown(e: KeyboardEvent) {
  if (!showList.value) return;
  if (e.key === 'Escape') {
    showList.value = false;
    inputEl.value?.focus();
  }
}

// 使用ref保存函数引用，确保清理时能准确移除
const docClickHandler = ref(onDoc);
const keydownHandler = ref(onKeydown);

function toggleList(){
  showList.value = !showList.value;
  if (showList.value) {
    nextTick(() => {
      const btn = engineBtn.value;
      if (!btn) return;
      const r = btn.getBoundingClientRect();
      menuPos.value = { left: Math.round(r.left), top: Math.round(r.bottom + 8) };
    });
  }
}

onMounted(()=>{ 
  document.addEventListener('pointerdown', docClickHandler.value, true);
  document.addEventListener('keydown', keydownHandler.value);
});

onBeforeUnmount(()=>{
  document.removeEventListener('pointerdown', docClickHandler.value, true);
  document.removeEventListener('keydown', keydownHandler.value);
});
function focusInput(e: MouseEvent){
  // 点击引擎按钮或其弹层不强制聚焦输入框
  const t = e.target as HTMLElement;
  if (t.closest('.engine-wrap')) return;
  inputEl.value?.focus();
}

async function choose(id: string){
  try {
    showList.value = false;
    await engines.setDefault(id);
    // 保障在某些场景下（如导入或其它并发写入）状态一致
    await engines.reload();
    // Toast已经在engines.setDefault中处理了
  } catch(e) {
    console.error('Failed to choose engine:', e);
    try{ (window as any).gceToast?.('切换失败'); }catch{}
  }
}

function onSubmit(){
  const query = q.value.trim();
  if(!query) return;
  const tpl = currentEngine.value?.template || engines.defaultEngine?.template || 'https://www.baidu.com/s?wd=%s';
  const url = composeUrl(tpl, query);
  const target = settings.settings.openMode === 'newtab' ? '_blank' : '_self';
  window.open(url, target);
}
</script>
<style scoped>
.search{ 
  display:flex; align-items:center; gap:8px;
  width:60vw; max-width:100%; height:56px; 
  margin: 64px auto 24px;
  background: var(--glass-dark);
  border:1px solid var(--border);
  border-radius: 999px; padding: 0 8px 0 8px;
  box-shadow: 0 6px 18px rgba(0,0,0,.35);
  backdrop-filter: blur(4px);
  transition: box-shadow .2s ease, transform .2s ease;
  position: relative; z-index: 100; /* 降低层级，避免遮挡分组栏/弹层 */
  box-sizing: border-box;
}
.search:hover{ box-shadow: var(--shadow-dark); transform: translateY(-1px); }
.engine-wrap{ position:relative }
.engine{ width:36px; height:36px; border-radius:50%; border:1px solid var(--border); background:var(--card); color:var(--text); display:flex; align-items:center; justify-content:center; cursor:pointer }
.engine .logo{ width:18px; height:18px; object-fit:contain; border-radius:4px; display:block }
.engine-list{ position:absolute; left:0; top:44px; background:var(--glass-dark); backdrop-filter: blur(6px); border:1px solid var(--border); border-radius:12px; padding:6px; box-shadow: var(--shadow-dark); width:220px; z-index: 100002; pointer-events:auto }
.engine-item{ display:flex; align-items:center; gap:10px; width:100%; background:transparent; border:0; color:var(--text); padding:8px 10px; border-radius:8px; cursor:pointer }
.engine-item:hover{ background: rgba(255,255,255,.06) }
.engine-item .dot{ width:20px; height:20px; border-radius:50%; background:#2b2f3c; display:flex; align-items:center; justify-content:center; font-size:12px; color:#fff }
.engine-item .logo.sm{ width:16px; height:16px; object-fit:contain; border-radius:3px; display:block }
.engine-item .nm{ font-size:14px }
input{ flex:1; background:transparent; border:0; outline:none; padding:0 8px; color:var(--text); font-size:14px }

/* light 主题的专属样式：更明亮、更有层次 */
:host-context([data-theme='light']) .search{
  background: var(--glass-light);
  border-color: var(--border-light);
  box-shadow: 0 8px 28px rgba(0,0,0,.08);
}
:host-context([data-theme='light']) .engine-list{ background: var(--glass-light); border-color: var(--border-light); }
:host-context([data-theme='light']) .search:hover{
  box-shadow: var(--shadow-light);
}
:host-context([data-theme='light']) .engine{
  background:#fff;
  border-color: var(--border-light);
}
</style>
